/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,
        int& pi, int istart, int iend)
    {
        if (iend < istart) return nullptr;
        TreeNode* cur = new TreeNode(postorder[pi]);
        int curi = istart;
        while (curi <= iend)
        {
            if (postorder[pi] == inorder[curi])
                break;
            else
                curi++;
        }
        pi--;
        cur->right = _buildTree(inorder, postorder, pi, curi + 1, iend);
        cur->left = _buildTree(inorder, postorder, pi, istart, curi - 1);
        return cur;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        int pend = postorder.size() - 1;
        return _buildTree(inorder, postorder, pend, 0, inorder.size() - 1);
    }
};